package com.wuchao.controller;

import com.mysql.cj.util.StringUtils;
import com.wuchao.entity.User;
import com.wuchao.service.UserService;
import com.wuchao.util.Constants;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @Author wuchao66
 * @Date 2022/7/8 19:39
 * @Version 1.0
 */
@org.springframework.stereotype.Controller
/*@RestController//只返回结果，没有页面只有MOdel*/
public class Controller {
    @Resource
    private UserService userService;
    @RequestMapping({"main","sys/main"})
    public String main(){
        return "main";
    }
    @RequestMapping("find")
    public ModelAndView find(@RequestParam(value = "id",required = false,defaultValue = "1") int id){
        User user = userService.selectByPrimaryKey(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user",user);
        modelAndView.setViewName("main");
        return modelAndView;
    }
    @RequestMapping(value = {"load","sys/load"})
    public String load(){
        return "load";
    }
    @RequestMapping("bug")
    public String bug(){
        throw new RuntimeException("主动垃圾");
        //return "load";
    }
    @RequestMapping("logout")
    public String logout(HttpSession session,Model model){
        session.invalidate();
        model.addAttribute("logout","注销成功");
        return "load";
    }
    @RequestMapping("loading")
    public ModelAndView loading(Model model, String username, String password, HttpServletRequest request, HttpServletResponse response){
        int i = userService.loadByUsernameAndPwd(username, password);
        HttpSession session = request.getSession();
        if(i>0){
            ModelAndView modelAndView = new ModelAndView();
            session.setAttribute(Constants.USER_SESSION,username);
            modelAndView.setViewName("success");
            return modelAndView;
        }else{
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("isload","error");
            modelAndView.setViewName("load");
            return modelAndView;
        }
    }
    @RequestMapping("main1/{name}")
    public String main1(@PathVariable String name, Model model){
        model.addAttribute("name",name);
        return "main";
    }

    @RequestMapping({"sys/showMain1","sys/showMain2"})
    public String showMain(){//如果没有sesion 拦截不让去 集合名字
        return "showMain";
    }
    @RequestMapping("show404")
    public String show404(){//全局异常捕捉
       throw new RuntimeException();
    }
    @RequestMapping("loading1")
    public String loading1(){//进入登录界面
        return "loading1";
    }
    @RequestMapping("showload")//系统的类不直接传？？？？
    public String showload(String username,String pwd,
                           Model model,HttpServletRequest request){//登录
        int load = userService.load(username, pwd);
        if(load>0){//判断成功否
            HttpSession session = request.getSession();
            session.setAttribute(Constants.USER_SESSION,username);//常量存值
            session.setMaxInactiveInterval(30);
            model.addAttribute("username",username);
            return "showMain";//return  "forward:showMain";//请求
        }else{
            model.addAttribute("isload","账户或者密码错误");
            return "loading";//return  "redirect:loading";//响应
        }
    }@RequestMapping(value = "loginout")
    public String loginout(HttpSession session,Model model){//注销
        session.invalidate();
        model.addAttribute("loginout","注销成功");
        return "loading";
    }

    @RequestMapping(value = "model1/{name}")
    public String model1(@ModelAttribute("name")@PathVariable String name){//注销
        return "model1";
    }
    @RequestMapping(value = "fm")
    public ModelAndView fm(){//fm
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.selectByPrimaryKey(1);
        modelAndView.addObject("user",user);
        modelAndView.setViewName("main");
        return modelAndView;
    }
  /*  @RequestMapping(value = "model2")
    public String model2(@Valid String name, BindingResult bindingResult){//注销
        return "404";
    }*/

    /*/**
     * @Author wuchao66
     * @Date ${DATE} ${TIME}
     * @PackageName:${PACKAGE_NAME}
     * @ClassName: ${NAME}
     * @Description: TODO文件上传
     * @Param 多文件
     * @Version 1.0
     */
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public ModelAndView imageSingle(HttpSession session,HttpServletRequest request,@RequestParam(value = "files",required = false) MultipartFile [] files) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        //得到文件的上传路径
        String newPath =request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        //循环遍历文件
        for(MultipartFile file : files){
            if(file!=null){//非空
                //源文件名
                String oldname=file.getOriginalFilename();
                //源文件后缀
                String extension = FilenameUtils.getExtension(oldname);
                //文件大小
                int filesize=500000;
                if(file.getSize()>filesize){
                    modelAndView.addObject("fileError","文件大小超过了");
                    modelAndView.setViewName("404");
                    return modelAndView;
                }//文件格式
                if(extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png")
                        || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("pneg")){
                        String newname=System.currentTimeMillis()+new Random().nextInt(100000) +"_wc.jpg";//新名字
                    //新文件
                    File newfile=new File(newPath,newname);
                    if(!newfile.exists()){
                        newfile.mkdirs();
                    }//传输
                    file.transferTo(newfile);
                    modelAndView.addObject("fileinfo","文件上传成功");
                    modelAndView.addObject("fileinfo2",newPath);
                    modelAndView.setViewName("main");
                    return modelAndView;
                }else{
                    modelAndView.addObject("fileError","文件格式不对");
                    modelAndView.setViewName("404");
                    return modelAndView;
                }

            }else{
                modelAndView.addObject("fileError","文件为空");
                modelAndView.setViewName("404");
                return modelAndView;
            }
        }

        return modelAndView;

    }
    /*/**
     * @Author wuchao66
     * @Date ${DATE} ${TIME}
     * @PackageName:${PACKAGE_NAME}
     * @ClassName: ${NAME}
     * @Description: TODO 文件上传
     * @Param 协议请求  文件数组
     * @Version 1.0
     */
    @RequestMapping(value = "uploading",method = RequestMethod.POST)
   public ModelAndView uploading(@RequestParam(name = "files",required = false) MultipartFile[] files,HttpServletRequest request) throws IOException {
        ModelAndView modelAndView = new ModelAndView();//新建模型视图
        if(files!=null){//如果文件不为空
            //1)拿到新的上传地址
            HttpSession session = request.getSession();//得到本次会话地址
            //2)新地址
            String  newpath=session.getServletContext().getRealPath("statics"+File.separator+"newUploadFiles");
            for(MultipartFile file : files){//遍历数组
                //3)文件大小
                int filesize=50000;//限制文件大小
                long size = file.getSize();
                if(size>filesize){
                    throw new RuntimeException("文件太大");//404
                }else{
                    //4)文件格式
                    //先拿原始文件名
                    String originalFilename = file.getOriginalFilename();
                    //得到扩展名
                    String extension = FilenameUtils.getExtension(originalFilename);
                    //判断格式
                    if(extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png")
                            || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("pneg")){
                    //5）创建新文件名，防止重名
                        String newname=System.currentTimeMillis()+new Random().nextInt(100000)+"_chaoge.jpg";
                    //6)创建新文件
                        File newFile=new File(newpath,newname);
                        //7)如果文件目录不存在那就新建
                        if(!newFile.exists()){
                            newFile.mkdirs();
                        }
                        //8)文件传输
                        file.transferTo(newFile);
                        modelAndView.addObject("fileinfo","文件已经上传成功");
                        modelAndView.addObject("newpath",newpath);
                        modelAndView.setViewName("final");
                    }else{
                        throw new RuntimeException("文件格式不对");//404
                    }


                }


            }
            return modelAndView;
        }else{
            throw new RuntimeException("文件为空");//404
        }
    }
    /*@GetMapping //查询
@PutMapping //修改
@PostMapping //增加
@DeleteMapping //删除*/
//knife4j swagger 接口测试，前后端分离。jsp
    /*/**
     * @Author wuchao66
     * @Date ${DATE} ${TIME}
     * @PackageName:${PACKAGE_NAME}
     * @ClassName: ${NAME}
     * @Description: TODO rest风格
     * @Param model
     * @Version 1.0
     */
    @RequestMapping(value = "showFinal/{name}/{id}",produces = "application/json;charset=UTF-8")
    public String showFinal(@PathVariable @ModelAttribute /*@Valid*/ String name,/*BindingResult bindingResult,*/
                            @PathVariable @ModelAttribute int id){
       /* User user = userService.selectByPrimaryKey(1);
        model.addAttribute("user",user);*///存好值
      /*
        model.addAttribute("name",name);
        model.addAttribute("id",id);*/
        return "final";
    }

}
